package com.lemurian.bankdata.action.base;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.lite.utils.GlobalFunction;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.CategoryService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.Category;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

public class CategoryAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = 1L;
	
	private BankDataLogger log = BankDataLogger.getLogger(CategoryAction.class.getSimpleName());

	private Category category = new Category();
	private List<Category> categories;
	
	private int parentId = 0;
	private int id = 0;
	
	private List<Category> parents = new ArrayList<Category>();
	
	private User user;
	private BankDataPrincipal principal;
	
	@Autowired private CategoryService categoryService;
	
	@Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	@Override
	public void prepare() throws Exception {
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
		
		if(id > 0) {
			category = (Category) categoryService.findById(id);
			if(category != null && category.getParent() != null) {
				parentId = category.getParent().getId();
			}
		}
	}
	
	@Override
	public String list() {
		log.info("list Category");

        setPreviousPage(GeneralConstant.LIST);
        try {
            PartialList<Category> partialList = categoryService.findByCriteria(getStart(), getCount(),
                    getAscDesc().equalsIgnoreCase("asc") ? Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "id") : Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "id"),
            		category.getName() != null && category.getName().length() > 0 ? Restrictions.ilike("name", category.getName(), MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
    				category.getDescription() != null && category.getDescription().length() > 0 ? Restrictions.ilike("description", category.getDescription(), MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1))
                    );
            
            categories = partialList.getList();

            setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
            setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));
            
            partialList = null;
            
        } catch (Exception e) {
            return INPUT;
        }
        setMappedRequest(GeneralConstant.LIST);
        return SUCCESS;
	}
	
	@Override
	public String add() {
		setPreviousPage(GeneralConstant.ADD);
		
		getSession().put(GeneralConstant.TIME_IN_SESSION, new Date());
		
		if(parents == null || parents.size() ==0) parents = categoryService.findAll();

		setMappedRequest(GeneralConstant.SAVE);
		return SUCCESS;
	}
	
	@Override
	public String save() {
		
		try {
			
			String message = "";
			if(id > 0) {
				category.setUpdateBy(user.getName());
				category.setUpdateDate(new Timestamp(System.currentTimeMillis()));
				
				message = "Update";
                userActivityLog = new LogHelper(user, UserActivityType.UPDATE_CATEGORY);
			} else {
				category.setCreateBy(user.getName());
				category.setCreateDate(new Timestamp(System.currentTimeMillis()));
				
				message = "Add";
                userActivityLog = new LogHelper(user, UserActivityType.ADD_CATEGORY);
			}
			
			category.setParent(null);
			
			Category parent = null;
			if(parentId>0) {
				parent = (Category) categoryService.findById(parentId);
			}
			
			if(parent != null) {
				category.setParent(parent);
			}
			
			categoryService.save(category);
			
			try {
                message += " " + category.getName() + " is success";
                addCustomActionMessage(message);
                
                log.sInfo(" :: User [%s:%s] is successfully save Category [%s:%s]", user.getId(), user.getName(), category.getId(), category.getName());
                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
            } catch (Exception e) {
                message += " " + category.getName() + " is failed, message : "+e.getMessage();
                addCustomActionError(message);
                log.sInfo(" :: Error was raised when User [%s:%s] save Category [%s:%s]", user.getId(), user.getName(), category.getId(), category.getName());
                
                //set activity log status into failed
                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
                userActivityLog.setErrorMsg(e.getMessage());
            }
            
            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
            userActivityLog.setStartDate((Date) getSession().get(GeneralConstant.TIME_IN_SESSION));
            userActivityLog.getAdditionalParams().add(category.getName());
            userActivityLogService.saveUserActivity(userActivityLog);
            getSession().remove(GeneralConstant.TIME_IN_SESSION);
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		setMappedRequestFullPath("/CategoryAction_list.do");
		return GeneralConstant.REDIRECT;
	}

	@Override
	public String delete() {
		try {
			parents = categoryService.getParents(category.getId());
			
			for(Category c : parents) {
				Category cat = (Category) categoryService.findById(c.getId());
				categoryService.delete(cat);
			}
			
			addCustomActionMessage("Successfully delete "+category.getName());
			
			categoryService.delete(category);
			
		} catch (Exception e) {
			addCustomActionError("Cannot delete a parent row !");
		}
		
		setMappedRequestFullPath("CategoryAction_list.do");
		return GeneralConstant.REDIRECT;
	}

	@Override
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public List<Category> getCategories() {
		return categories;
	}

	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}

	public int getId() {
		return id;
	}

	public void setId(String id) {
		int id_ = 0;
		if(id != null && !id.equalsIgnoreCase("0")) {
			id = GlobalFunction.decodeParameter(id);
	        id_ = Integer.parseInt(id);
		}
        this.id = id_;
	}

	public int getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		int id_ = 0;
		if(parentId != null && !parentId.equalsIgnoreCase("0")) {
			parentId = GlobalFunction.decodeParameter(parentId);
	        id_ = Integer.parseInt(parentId);
		}
        this.parentId = id_;
		
	}

	public List<Category> getParents() {
		return parents;
	}

	public void setParents(List<Category> parents) {
		this.parents = parents;
	}
	
}